package com.venue.hjt.venueclass.ui



import android.app.AlertDialog
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.util.Base64
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.*


import com.venue.hjt.venueclass.R
import com.venue.hjt.venueclass.adapter.KotlinPagerAdapter
import com.venue.hjt.venueclass.bean.API
import com.venue.hjt.venueclass.db.CardDao
import com.venue.hjt.venueclass.db.CardStudent
import com.venue.hjt.venueclass.db.VenueSign
import com.venue.hjt.venueclass.fragment.*
import com.venue.hjt.venueclass.model.FActivityModel
import com.venue.hjt.venueclass.service.LocalService
import com.venue.hjt.venueclass.service.RemoteService
import com.venue.hjt.venueclass.utlis.*
import kotlinx.android.synthetic.main.activity_main2.*
import okhttp3.Call
import org.jetbrains.anko.imageResource
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.lang.Exception
import java.lang.ref.SoftReference
import java.text.SimpleDateFormat
import java.util.*

class Main2Activity : AppCompatActivity() , TabLayout.OnTabSelectedListener, View.OnClickListener {
    override fun onClick(p0: View?) {
        when (p0!!.id) {
        //登录
            R.id.bt_login -> {
                val name = et_name!!.text.toString().trim { it <= ' ' }
                val pwd = et_pwd!!.text.toString().trim { it <= ' ' }
                //收起键盘
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(dialog!!.window!!.decorView.windowToken,
                        0)
                mainModel!!.Login(name, pwd)
            }
            R.id.bt_close->{
                dialog!!.dismiss()
                APPUtlis.backgroundAlpha(this@Main2Activity, 1f)
            }
            R.id.tv_ClassName->{
                try {
                    showLoginDialog(0)
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
//                val intent=Intent(this,VenueActivity::class.java)
//                startActivity(intent)
            }
        }
    }

    /**
     * 将从Message中获取的，表示图片的字符串解析为Bitmap对象
     *
     * @param picStrInMsg
     * @return
     */
    fun decodeImg(picStrInMsg: String): Bitmap? {
        var bitmap: Bitmap? = null

        var imgByte: ByteArray? = null
        var input: InputStream? = null
        try {
            imgByte = Base64.decode(picStrInMsg, Base64.DEFAULT)
            val options = BitmapFactory.Options()
            options.inSampleSize = 8
            input = ByteArrayInputStream(imgByte)
            val softRef = SoftReference(BitmapFactory.decodeStream(input, null, options))
            bitmap = softRef.get() as Bitmap
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (imgByte != null) {
                imgByte = null
            }

            if (input != null) {
                try {
                    input.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return bitmap
    }
    override fun onTabReselected(tab: TabLayout.Tab?) {

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        val img=tab!!.customView!!.findViewById<ImageView>(R.id.image)
        setIma1(img)
        val text=tab.customView!!.findViewById<TextView>(R.id.tab_item_text)
        text!!.textSize = 20f
        text.setTextColor(resources.getColor(R.color.colorMo))
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        viewpager.currentItem=tab!!.position
        val img=tab.customView!!.findViewById<ImageView>(R.id.image)
        val text=tab.customView!!.findViewById<TextView>(R.id.tab_item_text)
        text!!.textSize = 30f
//        text!!.setTextColor(resources.getColor(R.color.colorAccent))
        setIma(img)

        when (tab.position) {
            0->{text.setTextColor(resources.getColor(R.color.colorNews))}
            1->{text.setTextColor(resources.getColor(R.color.colorKaoqi))}
            2->{text.setTextColor(resources.getColor(R.color.colorHome))}
            3->{text.setTextColor(resources.getColor(R.color.colorBanji))}
            4->{text.setTextColor(resources.getColor(R.color.colorPhoto))}
        }
    }

    var mainModel: FActivityModel?=null
    var homeReceiver:AHomeReceiver?=null
    var isCard=false
    var group_id=""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar!!.hide()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        setContentView(R.layout.activity_main2)
        mainModel=FActivityModel(this)
//      动态注册广播
        homeReceiver= AHomeReceiver()
        registerReceiver(homeReceiver, filter())
        val locationUtlis = LocationUtlis(applicationContext)
        locationUtlis.Location()
        getNamePwd()
        setTab()
        setItem()
//        val queryVenueEvaluateType = CardDao.queryVenueEvaluateType("1")
//        DialogUtlis().showPDialog(this@Main2Activity,queryVenueEvaluateType,"","","","","")
        tab.addOnTabSelectedListener(this)
        tv_ClassName!!.setOnClickListener(this)
        viewpager!!.currentItem =2
        viewpager!!.offscreenPageLimit=5
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    tv_classtime.text = ClassCalendar.getIntTimes()
                    tbCard.requestFocus()
                    val time= ClassCalendar.getIntDayVenue()
                    val mTime = mainModel!!.time
                    val str=APPUtlis.getTimeExpend(time,ClassCalendar.getIntDayVenue1()+" "+mTime.start_time)
                    val list=str.split(":")
                    val parseInt = Integer.parseInt(list[0])
                    val parseInt1 = Integer.parseInt(list[1])
                    Log.e("ATG",list[0]+"  "+list[1]+"   "+"  "+str)
                    if(mTime.end_time == "0"){
                        isCard=false
                    }else if (parseInt<=0&&parseInt1<=1){
                        isCard=true
//                        group_id=mTime.id
                        val groups = mTime.groups
                        if (groups.size!=0){
                            group_id= groups[0].booking_id
                        }
                        Log.e("ATG", " true $group_id  id")
                    }else{
                        isCard=false
                    }
                }
            }
        },10000, 5000)
        tv_ClassName.text=mainModel!!.className()
        tv_Day.text=ClassCalendar.getStringDay()
        arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, initialList)
        lv_debug.adapter = arrayAdapter
        initIdNumber()
        val class_no = PrefUtild.getString(applicationContext, "class_no", "")
        if (class_no != "") {
            val intent = Intent(this, LocalService::class.java)
            startService(intent)
            val intent1 = Intent(this, RemoteService::class.java)
            startService(intent1)
        }
    }

    private fun setTab(){
        //设置tab的模式
        tab.tabMode=TabLayout.MODE_FIXED
        /**
         * 第一种：initdata()!!
         * 第二种使用listof
         */
        viewpager.adapter= KotlinPagerAdapter(initData(),supportFragmentManager)
        //让tab和viewpager关联起来
        tab.setupWithViewPager(viewpager)
    }
    /**
     * 设置tabitem
     * */
    private fun setItem() {
        tab.getTabAt(0)?.customView=getTabView(0)
        tab.getTabAt(1)?.customView=getTabView(1)
        tab.getTabAt(2)?.customView=getTabView(2)
        tab.getTabAt(3)?.customView=getTabView(3)
        tab.getTabAt(4)?.customView=getTabView(4)
    }
    private fun setIma1(image: ImageView) {
        val para: ViewGroup.LayoutParams = image.layoutParams
        para.height = 90
        para.width = 90
        image.layoutParams = para
    }
    private fun setIma(image: ImageView) {
        val para: ViewGroup.LayoutParams = image.layoutParams
        para.height = 120
        para.width = 120
        image.layoutParams = para
    }
    /**
     * fragment 添加到集合中
     *  使用listof 代替
     * */
    private fun initData() : ArrayList<BaseFragment> {
        val mList = ArrayList<BaseFragment>()
        val tab1 = TabDongFragment()
        val tab2 = TabRecordFragment()
        val tab3 = TabHomeFragment()
        val tab4 = TabJJFragment()
        val tab5 = TabPhotoFragment()
        mList.add(tab1)
        mList.add(tab2)
        mList.add(tab3)
        mList.add(tab4)
        mList.add(tab5)
        return mList
    }
    private var bl_debug = true
    private fun initIdNumber() {
        tbCard.requestFocus()
        tbCard.setOnEditorActionListener { _, _, _ ->
            val strCardNo = tbCard.text.toString().trim { it <= ' ' }
            Log.e("ATG", strCardNo)
            val card = CardDao.queryLove(strCardNo)
            for (i in card.indices) {
                if (card[i].type == 0) {
                    if (bl_debug) {
                        initialList.add(0, ClassCalendar.getStringtHour() + " 设备号:" + android.os.Build.SERIAL)
                        arrayAdapter!!.notifyDataSetChanged()
                        lv_debug.visibility = View.VISIBLE
                        bl_debug = false
                    } else {
                        lv_debug.visibility = View.GONE
                        bl_debug = true
                    }
                }else if (card[i].type == 1) {
                    if (isCard){
                        val id = card[i].cardStudent.id
                        val queryGroupId = CardDao.queryGroupId(group_id + id)
                        if (queryGroupId.size!=0){
                            DialogUtlis.showStudentDialog(this@Main2Activity,card[i].cardStudent.student_url)
//                            http://129.1.2.243/hjtgrow/public/boardApi/venue/booking/signin?sno=98&booking_id=1&signin_id=8888&card_no=111111&signin_time=2018-03-16%2010:28&img=%E2%80%9C%E2%80%9D
                            val sign=VenueSign(group_id + id,queryGroupId[0].booking_id,queryGroupId[0].member_id,card[i].cardStudent.card_no,ClassCalendar.getCardtime(),0,false)
                            CardDao.insertVenueSign(sign)
                            Log.e("ATG",API.VENUESIGN+Constant.SNO+"&booking_id="+queryGroupId[0].booking_id+"&signin_id="+queryGroupId[0].member_id+"&card_no="+card[i].cardStudent.card_no+"&signin_time="+ClassCalendar.getCardtime())
                        }
                    }else{
                        val card = CardDao.queryLove(strCardNo)
                        for (i in card.indices) {
                            if (card[i].type == 0) {

                            }else if (card[i].type == 1) {
                                val intent=Intent(this@Main2Activity,VenuePersonalActivity::class.java)
                                intent.putExtra("student_no", card[i].cardStudent.id)
                                startActivity(intent)
                            }
                        }
                    }
                }
            }

            tbCard.setText("")
            false
        }
    }
//    private var bl_debug = true
    var initialList: MutableList<String> = ArrayList()
    private var arrayAdapter: ArrayAdapter<*>? = null
    /**
     * 判断当前是否登录
     */
    private fun getNamePwd() {
        if (mainModel!!.isnamepwd) {
            try {
                showLoginDialog(1)

            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
        }
    }
    private fun getTabView(position: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_item, null)
        val iv_head=view.findViewById<TextView>(R.id.tab_item_text)
        val im=view.findViewById<ImageView>(R.id.image)
        //我们可以给库函数 arrayOf() 传递每一项的值来创建Array，arrayOf(1, 2, 3) 创建了一个[1, 2, 3] 这样的数组
        val image = arrayOf(R.mipmap.news,R.mipmap.kaoqin,R.mipmap.home,R.mipmap.banji,R.mipmap.photo)
        val list=listOf("动态","场馆记录","首页","学校简介","学校相册")
        iv_head.text=list[position]
//        im.setImageResource(image[position])
        im.imageResource=image[position]
        return view
    }

    private var et_name: EditText?=null
    private var et_pwd: EditText?=null
    private var bt_login: Button?=null
    private var bt_close: Button?=null
    private var dialog: AlertDialog? = null
    @Throws(PackageManager.NameNotFoundException::class)
    private fun showLoginDialog(i: Int) {
        val inflater = layoutInflater
        val view = inflater
                .inflate(R.layout.dialog_login, null)
        et_name = view.findViewById(R.id.et_name)
        et_pwd = view.findViewById(R.id.et_pwd)
        bt_login = view.findViewById(R.id.bt_login)
        bt_close = view.findViewById(R.id.bt_close)
        bt_login!!.setOnClickListener(this)
        bt_close!!.setOnClickListener(this)
        val tv_versionName = view.findViewById<TextView>(R.id.tv_versionName)
        tv_versionName.text = "当前版本：" + APPUtlis.packageMas(this)
        dialog = AlertDialog.Builder(this).create()
        dialog!!.setCancelable(false)
        if (i == 0) {
            bt_close!!.visibility= View.VISIBLE
        }
        APPUtlis.backgroundAlpha(this, 0.06f)
        dialog!!.setOnKeyListener({ dialog, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
                if (i == 1) {
                    finish()
                } else if (i == 0) {
                    dialog.dismiss()
                }
                APPUtlis.backgroundAlpha(this, 1f)
            }
            false // 默认返回 false
        })
        dialog!!.setView(view)
        dialog!!.show()
    }
    /**
     * 广播类
     */
    inner class AHomeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                Constant.LOGIN -> {
                    val type = intent.getStringExtra("type")
                    if (type == "1") {
                        val loginErr = intent.getStringExtra(Constant.LOGIN)
                        Toast.makeText(this@Main2Activity,loginErr, Toast.LENGTH_LONG).show()
                    } else if (type == "2") {
                        dialog!!.dismiss()
                        val intent= Intent()
                        intent.action= Constant.HOMETEXT
                        sendBroadcast(intent)
                        APPUtlis.backgroundAlpha(this@Main2Activity, 1f)
                        tv_ClassName.text=mainModel!!.className()
                        viewpager!!.currentItem =2
                        intent.action=Constant.JIANJIE
                        sendBroadcast(intent)
                        intent.action=Constant.BANNER
                        sendBroadcast(intent)
                        intent.action=Constant.ARTICLR
                        sendBroadcast(intent)
                    }
                }
                Constant.WEATHER->{
                    val weather = intent.getStringExtra(Constant.WEATHER)
                    tv_Weather.text=weather
                }
                Constant.ERR -> {
                    val err = intent.getStringExtra(Constant.ERR)
                    initialList.add(0, err)
                    arrayAdapter!!.notifyDataSetChanged()
                }
            }
        }
    }
    /**
     * @return IntentFilter 广播
     */
    private fun filter(): IntentFilter {
        val filter = IntentFilter()
        filter.addAction(Constant.WEATHER)//天气
        filter.addAction(Constant.LOGIN)//登录
        filter.addAction(Constant.ERR)//调试
        return filter
    }
}

